package com.sxt.commons.xml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

/**
 * Created by Administrator on 2016/7/26.
 */
public class XMLParser<T> {
    public T xmlToBean(String xml,Class classType){
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(classType);
            Unmarshaller unMarshaller = context.createUnmarshaller();
            t = (T)unMarshaller.unmarshal(new StringReader(xml));
            System.out.println(t);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }

    /**
     * java对象转换为xml
     * */
    public String beanToXml(T t){
        StringBuffer buffer = new StringBuffer();
        JAXBContext context;
        Marshaller marshaller;
        try {
            context = JAXBContext.newInstance(t.getClass());
            marshaller = context.createMarshaller();
            marshaller.marshal(t, new File("test.xml"));
            InputStreamReader reader = new InputStreamReader(new FileInputStream("test.xml"));
            int temp;
            while((temp = reader.read())!=-1){
                buffer.append((char)temp);
            }
            System.out.println(buffer);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
